/* eslint-disable */
//常用方法集合
export default {
  countDownClock(time) {
    let times = Math.floor(time / 1000);
    let secondNum = times % 60;
    let minuteNum = Math.floor((times / 60) % 60);
    let hourNum = Math.floor((times / (60 * 60)) % 24);
    let dayNum = Math.floor(times / (60 * 60 * 24));
    let str;

    if (dayNum > 0) {

      str = dayNum + '天 ' + (hourNum > 9 ? hourNum : '0' + hourNum) + ':' + (minuteNum > 9 ? minuteNum : '0' +
        minuteNum) + ':' + (secondNum > 9 ? secondNum : '0' + secondNum);

      // console.log(str,1)
      return str
    } else if (hourNum > 0) {

      str = (hourNum > 9 ? hourNum : '0' + hourNum) + ':' + (minuteNum > 9 ? minuteNum : '0' + minuteNum) + ':' +
        (secondNum > 9 ? secondNum : '0' + secondNum)
      // console.log(str,2)
      return str;
    } else if (minuteNum > 0) {

      str = '00:' + (minuteNum > 9 ? minuteNum : '0' + minuteNum) + ':' + (secondNum > 9 ? secondNum : '0' +
        secondNum);
      // console.log(minuteNum,str,3)
      return str
    } else if (secondNum > 0) {

      str = '00:00:' + (secondNum > 9 ? secondNum : '0' + secondNum);
      // console.log(secondNum,4)
      return str
    } else {
      return '00:00:00'
    }

  },
  formatRichText(html) {
    //控制小程序中图片大小
    if (!html) {
      return "";
    }
    let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
      match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
      match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
      match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
      return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
      match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
        'max-width:100%;');
      return match;
    });
    // newContent = newContent.replace(/<br[^>]*\/>/gi, '');
    newContent = newContent.replace(/\<img/gi,
      '<img style="max-width:100%;height:auto;display:block;margin-top:10rpx;font-size:0;"');
    return newContent;
  },
  /**
   * 时间处理
   */
  patTime(val) {
    var beginTime = new Date()
    var time = val - beginTime
    var days = Math.floor(time / (24 * 3600 * 1000))

    var leave1 = time % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000))
    //计算相差分钟数
    var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000))

    //计算相差秒数
    var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
    var seconds = Math.round(leave3 / 1000)
    if (days > 0) {
      return days + '天' + hours + ':' + minutes + ':' + seconds
    } else {
      if (hours > 0) {
        return hours + ':' + minutes + ':' + seconds
      } else {
        if (minutes > 0) {
          return minutes + ':' + seconds
        } else {
          if (seconds > 0) {
            return seconds + '秒'
          } else {
            return '00:00'
          }
        }
      }
    }


  },
  /**
   * 金额保留两位小数点后，大小
   */
  priceBigSmall(value = 0, boolean = true, num = 36) {
	let size = num == undefined ? 36 : num
    // let val = (Math.floor((value || 0) * 100) / 100).toFixed(2);
    let val = this.precisionTrue(value, 2)
    let splitPrice = val.split(".");
    let price =
      `<span style="font-size:36rpx;font-weight: Regular;">￥${splitPrice[0]}.</span><span style="font-size:${size}rpx;font-weight: Regular;">${splitPrice[1]}</span>`;
    // 若boolean 为 false，则不带单位 ￥
    if (boolean == false) {
      price = price.replace(/￥/g, '')
    }
    return price
  },
  priceBigSmallFont16(value = 0, boolean = true, num = 36) {
  	let size = num == undefined ? 36 : num
    // let val = (Math.floor((value || 0) * 100) / 100).toFixed(2);
    let val = this.precisionTrue(value, 2)
    let splitPrice = val.split(".");
    let price =
      `<span style="font-size:32rpx;font-weight: Regular;">￥${splitPrice[0]}.</span><span style="font-size:${size}rpx;font-weight: Regular;">${splitPrice[1]}</span>`;
    // 若boolean 为 false，则不带单位 ￥
    if (boolean == false) {
      price = price.replace(/￥/g, '')
    }
    return price
  },
  priceBigSmallTwo(value = 0) {
    // let val = (Math.floor((value || 0) * 100) / 100).toFixed(2);
    let val = this.precisionTrue(value, 2)
    let splitPrice = val.split(".");
    let price =
      `<span style="font-size:22rpx;">￥</span>
	  ${splitPrice[0]}.<span style="font-size:22rpx;">${splitPrice[1]}</span>`;
    return price
  },
  // 进度正确
  precisionTrue(num, n) {
    if (n != undefined && (isNaN(n) || Number(n) > 17 || Number(n) < 0)) {
      throw new Error("输入正确的精度范围");
    }
    // 拆分小数点整数和小数
    // var num = this;
    var f = '';
    num = Number(num)
    if (Number(num) < 0) {
      num = -Number(num);
      f = '-';
    }
    var numList = num.toString().split(".");
    // 整数
    var iN = numList[0];
    // 小数
    var dN = numList[1];
    n = parseInt(n);
    if (isNaN(n) || Number(n) === 0) {
      // 0或者不填的时候，按0来处理
      if (dN === undefined) {
        return num + '';
      }
      var idN = Number(dN.toString().substr(0, 1));
      if (idN >= 5) {
        if (Number(iN) < 0) {
          iN = Number(iN) - 1
        } else {
          iN = Number(iN) + 1
        }
      }
      return iN + '';
    } else {
      var dNL = dN === undefined ? 0 : dN.length;
      if (dNL < n) {
        // 如果小数位不够的话，那就补全
        var oldN = num.toString().indexOf('.') > -1 ? num : num + '.';
        var a = Number(n) - dNL;
        while (a > 0) {
          oldN += '0';
          a--;
        }
        return oldN;
      }
      // 正常
      var olddN = dN.toString().substring(0, n);
      var dN1 = Number(dN.toString().substring(0, n));
      var dN2 = Number(dN.toString().substring(n, n + 1));
      if (dN2 >= 5) {
        dN1 += 1;
        if (olddN.length - dN1.toString().length > 0) {
          var olddNL = olddN.length - dN1.toString().length
          while (olddNL > 0) {
            dN1 = '0' + dN1
            olddNL--;
          }
        }

        if (dN1.toString().length > n) {
          if (Number(iN) < 0) {
            iN = Number(iN) - 1
          } else {
            iN = Number(iN) + 1
          }
          dN1 = '0';
          while (n > 1) {
            dN1 += '0'
            n--;
          }
        }
      } else {
        dN1 = olddN
      }
      return f + iN + '.' + dN1;
    }
  },
  priceBigSmallTherr(value) {
    let val = (Math.floor((value || 0) * 100) / 100).toFixed(2);
    let splitPrice = val.split(".");
    let price = `<span >￥</span>${splitPrice[0]}.<span>${splitPrice[1]}</span>`;
    return price
  },

  /**
   * 金额保留两位小数点
   */
  priceDecimals(value) {
    let val = (Math.floor((value || 0) * 100) / 100).toFixed(2);
    return val
  },
  /**
   * toast提示
   */
  toast(title, duration = 3000, mask = false, icon = 'none') {
    if (Boolean(title) === false) {
      return;
    }
    uni.showToast({
      title,
      duration,
      mask,
      icon
    });
  },
  getPrevPage() {
    var pages = getCurrentPages(); // 获取页面栈
    var prevPage = pages[pages.length - 2]; // 上一个页面
    return prevPage;
  },

  // 获取当前页面栈
  getCurrentPageFun(url) {
    let currentPage = getCurrentPages()
    uni.setStorageSync('toUrl', currentPage[currentPage.length - 1].route)
    uni.navigateTo({
      url: url
    })
  },

  // 清除当前页面栈路由缓存
  removeCurrenPage() {
    let currentPage = getCurrentPages()
    let toUrl = uni.getStorageSync('toUrl')
    let backNum = 0
    currentPage.map((item, index) => {
      if (item.route == toUrl) {
        backNum = index
      }
    })
    uni.navigateBack({
      delta: currentPage.length - backNum - 1
    })
    uni.removeStorageSync('toUrl')
  },

  /**
   * 开发环境全局打印日志
   * @param {Object} title
   */
  log(title) {
    if (process.env.NODE_ENV === 'development' && Boolean(title) === true) {
      console.log(JSON.stringify(title));
    }
  },
  /**
   * 异步获取设备信息
   */
  getInfoAsync() {
    return new Promise((resolve, reject) => {
      plus.device.getInfo({
        success(e) {
          resolve(e);
        },
        fail(e) {
          reject(e.message);
        }
      });
    });
  },
  /**
   * 安卓10不支持IMEI,则获取OAID
   */
  getOaidAsync() {
    return new Promise((resolve, reject) => {
      plus.device.getOAID({
        success(e) {
          resolve(e);
        },
        fail(e) {
          reject(e.message);
        }
      });
    });
  },
  /**
   * 获取一个随机数
   * @param {Object} min
   * @param {Object} max
   */
  random(min, max) {
    switch (arguments.length) {
      case 1:
        return parseInt(Math.random() * min + 1, 10);
        break;
      case 2:
        return parseInt(Math.random() * (max - min + 1) + min, 10);
        break;
      default:
        return 0;
        break;
    }
  },
  /**
   * 获取ios的IDFA
   */
  getIdfa() {
    let idfa = '';
    try {
      if ('iOS' == plus.os.name) {
        let manager = plus.ios.invoke('ASIdentifierManager', 'sharedManager');
        if (plus.ios.invoke(manager, 'isAdvertisingTrackingEnabled')) {
          let identifier = plus.ios.invoke(manager, 'advertisingIdentifier');
          idfa = plus.ios.invoke(identifier, 'UUIDString');
          plus.ios.deleteObject(identifier);
        }
        plus.ios.deleteObject(manager);
      }
    } catch (e) {
      console.error('获取idfa失败');
    }
    return idfa;
  },
  /*
   * obj 转 params字符串参数
   * 例子：{a:1,b:2} => a=1&b=2
   */
  objParseParam(obj) {
    let paramsStr = '';
    if (obj instanceof Array) return paramsStr;
    if (!(obj instanceof Object)) return paramsStr;
    for (let key in obj) {
      paramsStr += `${key}=${obj[key]}&`;
    }
    return paramsStr.substring(0, paramsStr.length - 1);
  },
  /*
   * obj 转 路由地址带参数
   * 例子：{a:1,b:2} => /pages/research/homepage/index?a=1&b=2
   */
  objParseUrlAndParam(path, obj) {
    let url = path || '/';
    let paramsStr = '';
    if (obj instanceof Array) return url;
    if (!(obj instanceof Object)) return url;
    paramsStr = this.objParseParam(obj);
    paramsStr && (url += '?');
    url += paramsStr;
    return url;
  },
  /*
   * 获取url字符串参数
   */
  getRequestParameters(locationhref) {
    let href = locationhref || '';
    let theRequest = new Object();
    let str = href.split('?')[1];
    if (str != undefined) {
      let strs = str.split('&');
      for (let i = 0; i < strs.length; i++) {
        theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
      }
    }
    return theRequest;
  },
  /**
   * 加密字符串
   */
  strEncode(str) {
    const key = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let l = key.length;
    let a = key.split('');
    let s = '',
      b,
      b1,
      b2,
      b3;
    for (let i = 0; i < str.length; i++) {
      b = str.charCodeAt(i);
      b1 = b % l;
      b = (b - b1) / l;
      b2 = b % l;
      b = (b - b2) / l;
      b3 = b % l;
      s += a[b3] + a[b2] + a[b1];
    }
    return s;
  },
  /**
   * 解密字符串
   */
  strDecode(str) {
    const key = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let l = key.length;
    let b,
      b1,
      b2,
      b3,
      d = 0,
      s;
    s = new Array(Math.floor(str.length / 3));
    b = s.length;
    for (let i = 0; i < b; i++) {
      b1 = key.indexOf(str.charAt(d));
      d++;
      b2 = key.indexOf(str.charAt(d));
      d++;
      b3 = key.indexOf(str.charAt(d));
      d++;
      s[i] = b1 * l * l + b2 * l + b3;
    }
    b = eval('String.fromCharCode(' + s.join(',') + ')');
    return b;
  },
  /**
   * 比较版本号
   */
  compareVersion(reqV, curV) {
    if (curV && reqV) {
      let arr1 = curV.split('.'),
        arr2 = reqV.split('.');
      let minLength = Math.min(arr1.length, arr2.length),
        position = 0,
        diff = 0;
      while (
        position < minLength &&
        (diff = parseInt(arr1[position]) - parseInt(arr2[position])) == 0
      ) {
        position++;
      }
      diff = diff != 0 ? diff : arr1.length - arr2.length;
      if (diff > 0) {
        if (position == minLength - 1) {
          return 1;
        } else {
          return 2;
        }
      } else {
        return 0;
      }
    } else {
      return 0;
    }
  },
  /**
   * H5复制
   */
  h5Copy(content) {
    let textarea = document.createElement('textarea');
    textarea.value = content;
    textarea.readOnly = 'readOnly';
    document.body.appendChild(textarea);
    textarea.select(); // 选择对象
    textarea.setSelectionRange(0, content.length); //核心
    let result = document.execCommand('Copy'); // 执行浏览器复制命令
    textarea.remove();
    const msg = result ? '复制成功' : '复制失败';
    this.toast(msg);
  },
  /**
   * app分享
   */
  handleAppShare(shareUrl, shareTitle, shareContent, shareImg) {
    let shareData = {
      shareUrl,
      shareTitle,
      shareContent,
      shareImg
    };
    appShare(shareData, res => {});
  },

  async handleWxH5Share(title, desc, link, imgUrl) {
    // #ifdef H5
    if ($mPayment.isWechat()) {
      if (uni.getSystemInfoSync().platform === 'android') {
        await $mPayment.wxConfigH5(link);
      }
      jweixin.ready(function() {
        // eslint-disable-next-line
        jweixin.updateAppMessageShareData({
          title, // 分享标题
          desc, // 分享描述
          link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl, // 分享图标
          success: function() {
            // 用户确认分享后执行的回调函数
          },
          cancel: function() {
            // 用户取消分享后执行的回调函数
          }
        });
        // eslint-disable-next-line
        jweixin.updateTimelineShareData({
          title, // 分享标题
          desc, // 分享描述
          link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl, // 分享图标
          success: function() {
            // 用户确认分享后执行的回调函数
          },
          cancel: function() {
            // 用户取消分享后执行的回调函数
          }
        });
      });
    }
    // #endif
  },

  //截取后四位数
  cutOut(value) {
    if (!value) {
      return '';
    }
    return value.substring(value.length - 4)
  },
  // 去掉字符串中的空格
  trim(str) {
    if (!str) {
      return '';
    }
    return str.replace(/\s*/g, '');
  },

  // 判断两个对象是否相同
  isObjectValueEqual(x, y) {
    // 指向同一内存时
    if (x === y) {
      return true;
    } else if (
      typeof x == 'object' &&
      x != null &&
      typeof y == 'object' && y != null
    ) {
      if (Object.keys(x).length != Object.keys(y).length) return false;

      for (var prop in x) {
        if (y.hasOwnProperty(prop)) {
          if (!this.isObjectValueEqual(x[prop], y[prop])) return false;
        } else return false;
      }

      return true;
    } else return false;
  },

  platformGroupFilter() {
    let platformGroup = 'tinyShop';
    // #ifdef H5
    if ($mPayment.isWechat()) {
      platformGroup = 'tinyShopWechat';
    } else {
      platformGroup = 'tinyShopH5';
    }
    // #endif
    // #ifdef MP-QQ
    platformGroup = 'tinyShopQqMp';
    // #endif
    // #ifdef MP-WEIXIN
    platformGroup = 'tinyShopWechatMp';
    // #endif
    // #ifdef MP-ALIPAY
    platformGroup = 'tinyShopAliMp';
    // #endif
    // #ifdef MP-QQ
    platformGroup = 'tinyShopQqMp';
    // #endif
    // #ifdef MP-BAIDU
    platformGroup = 'tinyShopBaiduMp';
    // #endif
    // #ifdef APP-PLUS
    switch (uni.getSystemInfoSync().platform) {
      case 'android':
        platformGroup = 'tinyShopAndroid';
        break;
      case 'ios':
        platformGroup = 'tinyShopIos';
        break;
    }
    // #endif
    return platformGroup;
  },
  countDown(ft, ct) {
    var ctime = ct || Math.floor(new Date().getTime())
    var time = ft * 1000 - ctime
    var days = Math.floor(time / (24 * 3600 * 1000))

    var leave1 = time % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000))
    //计算相差分钟数
    var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000))

    //计算相差秒数
    var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
    var seconds = Math.round(leave3 / 1000)
    console.log(days + ':' + hours + ':' + minutes + ':' + seconds)
    return days + ':' + hours + ':' + minutes + ':' + seconds
    // if(days >0){
    // 	return days+'天'+hours+':'+minutes+':'+seconds
    // }else{
    // 	if(hours >0){
    // 		return hours+':'+minutes+':'+seconds
    // 	}else{
    // 		if(minutes >0){
    // 			return minutes+':'+seconds
    // 		}else{
    // 			if(seconds>0){
    // 				return seconds+'秒'
    // 			}else{
    // 				return '00:00'
    // 			}
    // 		}
    // 	}
    // }


  },
  // 保留8位小数
  isToFixed(value, num) {
    if (value) {
      let val = this.precisionTrue(value, num)
      let splitPrice = val.split(".");
      let price =
        `<span style="font-size:16px;color:#FF211F">${splitPrice[0]}.</span><span style="font-size:16px;font-weight: normal;color:#FF721B">${splitPrice[1]}</span> 贡献值`;
      return price
    } else {
      return `<span style="font-size:16px;color:#FF211F">0.</span><span style="font-size:16px;font-weight: normal;color:#FF721B">00</span> 贡献值`;
    }
  },
  isToFixedNum(value, num) {
    if (value) {
      let val = this.precisionTrue(value, num)
      return val
    } else {
      return 0
    }
  },
  // 电话隐私保护
  phoneChange(tel) {
    if (tel) {
      let result = tel.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
      return result
    } else {
      return tel
    }
  },
  // 打电话
  callup(mobile) {
    uni.makePhoneCall({
      phoneNumber: mobile //仅为示例
    });
  },
  // 导航
  jumpLocation(latitude, longitude) {
    uni.getLocation({
      type: 'gcj02', //返回可以用于uni.openLocation的经纬度
      success: function(res) {
        uni.openLocation({
          latitude: Number(latitude),
          longitude: Number(longitude),
          success: function() {
            console.log('success');
          }
        });
      }
    });
  },
  // banner跳转
  imgLink(type, id, url, shopid) {
    if (type == "goods") {
      uni.navigateTo({
        url: "/pages/product/goods/goods?id=" + id + "&shopid=" + shopid,
      });
    } else if (type == "service") {
      // uni.navigateTo({
      //   url: "/pages/product/goods/serviceGood?id=" + id
      // });
    } else if (type == "point_goods") {
      // uni.navigateTo({
      //   url: "/pages/product/goods/IntegralGood?id=" + id
      // });
    } else if (type == "url") {
      if (/^http/.test(url)) {
        uni.navigateTo({
          url: "/pages/index/webView?linkUrl=" + url,
        });
      } else {
        uni.navigateTo({
          url
        });
      }
    } else if (type == 'inner_url') {
      uni.navigateTo({
        url
      });
    }
  },
  // 一行卡号脱敏
  bankAccount(value) {
    if (value) {
      let reg = /^(.{4})(?:\d+)(.{4})$/
      let str = value.replace(reg, "$1 **** **** $2")
      return str
    } else {
      return value
    }
  }
};
